package com.lkk.interaction;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lkk.data.ExcelDataEntity;
import com.lkk.data.ExcelDataException;
import com.lkk.data.Log;
import com.lkk.util.Constant;
import com.lkk.util.EntityListUtil;
import com.lkk.util.InterfaceUtil;

/**
 * 请求/响应操作类
 * @author admin
 *
 */
public class RestfulClient {
		//发送请求对象
		private CloseableHttpClient httpClient;
		//接收响应对象
		private CloseableHttpResponse httpResponse;
		//GET请求对象
		private HttpGet httpget;
		//POST请求对象
		private HttpPost httpPost;
		//JSON格式响应主体对象
		private JSONObject responseBody;
		
		
		/**
		 * 发送GET请求
		 * @param method 请求方式
		 * @param url 请求路径
		 * @throws ClientProtocolException
		 * @throws IOException
		 */
		public void sendRequest(String method,String url) throws ClientProtocolException, IOException {
			//获取发送请求对象
			httpClient = HttpClients.createDefault();
			//cookie保存对象
			CookieStore cookieStore = new BasicCookieStore();
			//发送对象设置cookie保存机制
	        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			//创建GET请求对象
			httpget = new HttpGet(url);
			//发送GET请求
			httpResponse = httpClient.execute(httpget);
		}
		
		/**
		 * 发送加密/非加密POST请求
		 * @param method 请求方法
		 * @param ifEncrypt 是否加密
		 * @param headers 消息头
		 * @param body 请求主体
		 * @param url 请求路径
		 * @throws ClientProtocolException
		 * @throws IOException
		 * @throws ExcelDataException
		 */
		public void sendRequest(String method,String ifEncrypt,Map<String, String> headers,JSONObject body,String url) 
						throws ClientProtocolException,IOException, ExcelDataException {
			//json串格式化
			String bodyString = JSON.toJSONString(body, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, 
			            SerializerFeature.WriteDateUseDateFormat);
			//打印请求主体信息
			Log.info("\n"+"requestbody:"+bodyString);
			//创建发送请求对象
			httpClient = HttpClients.createDefault();
			//cookie保存对象
			CookieStore cookieStore = new BasicCookieStore();
			//发送对象设置cookie保存机制
	        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			//创建POST请求对象
			httpPost = new HttpPost(url);
			//判断请求是否需要加密
			if(Constant.YES.equals(ifEncrypt.toUpperCase())){
				//将请求主体加密
				byte[] entity = InterfaceUtil.finalResponseHander(body.toString().getBytes("utf-8"));
				//post请求塞入转换为Stringentity格式的主体信息
				httpPost.setEntity(new StringEntity(new String(entity),"utf-8"));
			}else if(Constant.NO.equals(ifEncrypt.toUpperCase())) {
				//把响应主体对象转为StringEntity格式
				StringEntity entity = new StringEntity(body.toString());
				//post请求塞入主体信息
				httpPost.setEntity(entity);
			}else {
				//传参值错误
				throw new ExcelDataException();
			}
	        //获取消息头的key set集合
	        Set<String> set= headers.keySet();
	        //遍历消息头
	        for(Iterator<String> iterator = set.iterator();iterator.hasNext();) {
	        	//获取消息头的key值
	        	String key = iterator.next();
	        	//获取消息头的value值
	        	String value = headers.get(key);
	        	//塞到POST请求中
	        	httpPost.setHeader(key, value);
	        }
	        //发送POST请求
	        httpResponse = httpClient.execute(httpPost);
		}
		
		/**
		 * 获取响应头
		 * @return 返回的响应头
		 */
		public HashMap<String,String> getResponseHeader() {
			//获取响应头数组
			Header[] headers = httpResponse.getAllHeaders();
			//存储响应头的map
			HashMap responseHeader = new HashMap<String, String>();
			for(Header header:headers) {
				//获取响应头的key,value循环塞到map中
				responseHeader.put(header.getName(), header.getValue());
			}
			Log.info("responseHeader:"+responseHeader);
			return responseHeader;
		}
		
		/**
		 * 获取响应主体
		 * @param ifEncrypt 是否加密
		 * @return 返回响应主体信息
		 * @throws ParseException
		 * @throws IOException
		 * @throws ExcelDataException
		 */
		public JSONObject getResponseBody(String ifEncrypt) throws ParseException, IOException, ExcelDataException {
			//获取主体对象
			HttpEntity httpEntity = httpResponse.getEntity();
			//将主体对象按照utf-8格式转换为String对象
			String entityString = EntityUtils.toString(httpEntity,Constant.ENCODER);
			if(Constant.YES.equals(ifEncrypt.toUpperCase())) {
				//解密
				String entityResult = InterfaceUtil.preHandler(entityString.getBytes("utf-8"));
				//将String格式的主体对象转换为JSON对象格式
				responseBody = JSON.parseObject(entityResult);
			}else if(Constant.NO.equals(ifEncrypt.toUpperCase())) {
				responseBody = JSON.parseObject(entityString);
			}else {
				//传参值错误
				throw new ExcelDataException();
			}
			//json串格式化
			String responseBodyString = JSON.toJSONString(responseBody, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, 
			            SerializerFeature.WriteDateUseDateFormat);
			Log.info("\n"+"responsebody:"+responseBodyString);
			return responseBody;
		}
		
		/**
		 * 获取响应的状态码
		 * @return 返回响应状态码
		 */
		public int getResponseCode() {
			//获取头部信息
			StatusLine statusLine = httpResponse.getStatusLine();
			//获取响应码
			int StatusCode = statusLine.getStatusCode();
			return StatusCode;
		}
	
		
}
